package com.example.firstflightcourier;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.jxpath.JXPathContext;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.DomSerializer;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import android.content.Context;
import android.content.res.Resources;
import android.util.Log;

public class Main extends SubClass{
	private static final String BASE_URL1 = "http://www.firstflight.net/n_contrac_new.asp?tracking1=D82564127";
	private static final Pattern PATTERN = Pattern.compile("<tr>\\s*<td>([^<]*)</td>\\s*<td>([^<]*)</td>\\s*<td>([^<]*)</td>\\s*</tr>", 34);
	private static final Pattern PATTERN1 = Pattern.compile("<tr>\\s*<td>([^<]*)</td>\\s*<td>([^<]*)</td>\\s*<td>([^<]*)</td>\\s*<td>([^<]*)</td>\\s*<td>([^<]*)</td>\\s*<td>([^<]*)</td>\\s*<td>([^<]*)</td>\\s*<td>([^<]*)</td>\\s*</tr>", 34);
	private Context context;
	public Main(Context context){
		this.context = context;
	}
	public void exec(){
		Log.d("####", "parsing1");
		
		try{
			HttpClient localHttpClient = buildHttpClient();
			GetMethod localGetMethod = new GetMethod("http://www.firstflight.net/n_contrac_new.asp?tracking1=D82564127");
			localGetMethod.setFollowRedirects(true);
		    localGetMethod.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
		    localGetMethod.setRequestHeader("Referer", "http://www.google.com");
		    
		    String str; //= getResponseBody(localGetMethod, localHttpClient.executeMethod(localGetMethod));
		    //Log.d("####", str.length()+" ");
		    
		    
		    Resources res = context.getResources();
	        InputStream in_s = res.openRawResource(R.raw.frst);

	        byte[] b = new byte[in_s.available()];
	        in_s.read(b);
	        str = new String(b);
	        //String str1 = cleanHtml(str);
	        TagNode tagNode = new HtmlCleaner().clean(str);
		    
//		    Matcher localMatcher = PATTERN.matcher(str1);
//		    
//		    while(localMatcher.find()){
//		    	Log.d("####", localMatcher.group(1).trim());
//		    	Log.d("####", localMatcher.group(2).trim());
//		    	Log.d("####", localMatcher.group(3).trim());
//		    }
//		    
//		    Matcher localMatcher1 = PATTERN1.matcher(str1);
//		    while(localMatcher1.find()){
//		    	Log.d("####", localMatcher.group(1).trim());
//		    	Log.d("####", localMatcher.group(2).trim());
//		    	Log.d("####", localMatcher.group(3).trim());
//		    	Log.d("####", localMatcher.group(4).trim());
//		    	Log.d("####", localMatcher.group(5).trim());
//		    	Log.d("####", localMatcher.group(6).trim());
//		    	Log.d("####", localMatcher.group(7).trim());
//		    	Log.d("####", localMatcher.group(8).trim());
//		    }
		   // Log.d("####", str1);
		    Document doc = null;
		    
		    //DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
	       // ByteArrayInputStream bais = new ByteArrayInputStream(str1.toString().getBytes("UTF8"));
	        //doc = builder.parse(bais); 
	        //bais.close(); 
		    
		    doc = new DomSerializer(new CleanerProperties()).createDOM(tagNode);
		    Log.d("####",  "-> "+toString(doc));

//	        JXPathContext ctx = JXPathContext.newContext(doc);
//	        String val = (String) ctx.getValue("/html/body/table/tbody/tr/td/table/tbody/tr[4]/td/table/tbody/tr/td/table/tbody/tr[2]/td[3]/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr[2]/td/table/tbody/tr[2]/td/table/tbody/tr[1]/td/strong");
	        
		    XPath xpath = XPathFactory.newInstance().newXPath();
		    //String val = (String) xpath.evaluate("//div//td[contains(@id, 'foo')]/text()", doc, XPathConstants.STRING);
		    String val = (String) xpath.evaluate("/html/body/table/tbody/tr/td/table/tbody/tr[4]/td/table/tbody/tr/td/table/tbody/tr[2]/td[3]/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr[2]/td/table/tbody/tr[2]/td/table/tbody/tr[1]/td/strong/text()", doc, XPathConstants.STRING);
		    
	        Log.d("####", val+"ok");
	        
//	        List entryNodes = ctx.selectNodes("/html/body/table/tbody/tr/td/table/tbody/tr[4]/td/table/tbody/tr/td/table/tbody/tr[2]/td[3]/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr[2]/td/table/tbody/tr[2]/td/table/tbody/tr[1]/td/strong");
//	        System.out.println("number of threadNodes " + entryNodes.size());
//	        int totalThreads = 0;
//	        for (Object each : entryNodes) {
//	            totalThreads++;
//	            Node eachEntryNode = (Node) each;
//	            JXPathContext msgCtx = JXPathContext.newContext(eachEntryNode);
//	            String title = (String) msgCtx.getValue("title");
//	        }
		    
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	protected HttpClient buildHttpClient(){
		HttpClientParams localHttpClientParams = new HttpClientParams();
		localHttpClientParams.setConnectionManagerClass(MultiThreadedHttpConnectionManager.class);
		localHttpClientParams.setSoTimeout(30000);
		localHttpClientParams.setConnectionManagerTimeout(30000);
	    return new HttpClient(localHttpClientParams);
	}
	
	public static String toString(Document doc) {
	    try {
	        StringWriter sw = new StringWriter();
	        TransformerFactory tf = TransformerFactory.newInstance();
	        Transformer transformer = tf.newTransformer();
	        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
	        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
	        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
	        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

	        transformer.transform(new DOMSource(doc), new StreamResult(sw));
	        return sw.toString();
	    } catch (Exception ex) {
	        throw new RuntimeException("Error converting to String", ex);
	    }
	}
	
}
